Repository navigation
Keep path conditions on the old value when a variable is reassigned - #549
Conversation
A path condition holds the condition both on variable names and on the
instances it was checked on. Assigning a variable dropped every path
condition that mentioned it, so a guard written to keep the assignment in
range (if (n <= 10 - t) t = t + n) did not prove it. Before a primitive
variable gets a new instance, its name in the path conditions is now
replaced by its current instance, which keeps them true; they are dropped
only when there is no instance to name the old value, or for objects.
This also covers ++ and --, which kept the condition on the name and so
applied it to the incremented value (if (t < 5) { t++; ... } assumed
t < 5 after the increment). After an if where only one branch continues,
the path condition is kept as that branch left it.
ErrorIfAssignment's second case assigned in a branch that cannot run
(a == 5 is never < 0); its guard is changed so the branch is reachable.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The else branch started from the path conditions the then branch left, and both branches' conditions stayed after the if, so a nested if (t > 0) return; in one branch made t <= 0 known in the other branch and after the if. Each branch now starts from the conditions before the if; after it, only the conditions both branches kept remain, or those of the only branch that reaches the code after it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Codex round 1: what was done
Pushed in 6f9ed76. |
A refinement that read a parameter before it was written (x == y after int x = y) named the parameter itself, and a parameter's name stands for its last instance: once y was written, x == y described the new value, so x > 0 and y = -1 contradicted each other and proved anything. A parameter that the method writes now gets an instance on entry, which such refinements name. The counterexample of ErrorAssignmentBeforeReturn names the entry value #x instead of x (displayed the same). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Codex review, round 2
The round 1 fix is verified: in a separate nested-if program, this branch reports errors both in the sibling |
Codex round 2: what was done
Pushed in 73c2c5f. |
Codex review, round 3No new false negative found. The repository was left unchanged. The earlier fixes held in verifier runs on both builds:
Additional assignment and control-flow probes and jump, switch, and finally probes reported the expected violations. I found no code-quality issue in the diff worth a separate finding. Nothing left to fix; the Codex loop for this PR ends here. |
Clean-code reviewAudit of this PR's own new code (clean-code-principles: SOLID, DRY, KISS, naming, functions).
|
Stacked on #549; review/merge after it. Fixes #543 Part of the loop invariant inference plan (#542). ## What and why `InvariantCandidates.of(x, x0, condition)` builds the candidate invariants of an `int` local variable `x` that a loop changes, in the manner of Liquid Types' qualifiers (Rondon, Kawaguchi, Jhala, PLDI 2008): - `x >= x0` and `x <= x0`, with `x0` the instance of `x` before the loop (it only grows or only shrinks; works for symbolic starts); - the order comparisons (`<`, `<=`, `>`, `>=`) among the top-level conjuncts of the loop condition that mention `x`, made non-strict so the iteration that ends the loop can keep them (`i < n` gives `i <= n`). Terms are limited to integer literals, `int` local variables and parameters, `+`, `-`, `*` and unary minus: fields and calls may change out of sight of the loop (PM decision on #542). Comparisons under `||` or `!` and `!=` give no candidate. Order is deterministic, duplicates are removed, and there are at most 6 candidates per variable (`MAX_PER_VARIABLE`, to be tuned in #547). Pure code, not used by the checker yet; the next PR (Houdini check, #544) proves the candidates before using them, so a candidate is only a guess and a wrong one can only cost precision. ## Plan change The plan had this PR based on `main` and independent of #538. It is stacked on #549 (#538) instead, so the stack is linear (#549 → this → #544 → #545): the Houdini step relies on #549 to stay sound (`x++` used to keep the loop condition on the incremented value, which could prove a non-inductive candidate), and the buffer loop from #537 then verifies in the stack itself. ## Tests `InvariantCandidatesTest` (8 unit tests): bounds from the value before the loop, none without an instance, weakening of each comparison kind, only comparisons that mention the variable, none from `||`/`!`/`!=`, only supported terms (field, call, cast, division, `long` literal rejected), the grouping of nested terms (`n - (n - 1)`), and the cap. Full suite passes locally; no change in what the verifier accepts. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Stacked on #550; review/merge after it. Fixes #544 Fixes #537 Fixes #479 Part of the loop invariant inference plan (#542). ## What and why A loop havocs every variable it changes: at the loop head a changed variable keeps only its declared refinement, so `for (int i = 0; i < 10; i++) use(i)` did not know `i >= 0` (#537). This PR infers invariants for the `int` local variables (and parameters) a loop changes, with the Houdini algorithm (Flanagan and Leino, FME 2001) over the candidates of #550 (Liquid Types qualifiers): 1. **Start check** (`new LoopInvariants`, before the havoc): keep the candidates that the facts before the loop prove (`x0` is the instance before the loop). 2. **Assume at the head** (`startIteration`): add the remaining candidates to the refinements of the loop-head instances (not as a path condition, which an assignment would rename or drop). 3. **Step check** (`recordNextIteration`): at the point where the next iteration starts (end of the body for `while`/for-each, after the update for `for`, after the condition for `do`-`while`, where the condition is now assumed since the next iteration only starts when it holds) drop each candidate not proved for the last instances. 4. **Continues:** the end of a body with continues is a join where `scanBody` havocs the changed variables again. There, the candidates and "`x` grew / shrank since the head" are kept when proved at every continue and at the fall-through end of the body (`atJoin`/`joined`), so a `for` update or a `do`-`while` condition that follows can still be checked. 5. Repeat until a check drops nothing, inside the existing `checkUntilFixpoint` loop (which already re-checks the body until typestates are stable and keeps only the errors of the last check). After 8 checks that dropped candidates, all are dropped (`MAX_ROUNDS`). All candidate proofs are silent (`checkStateSMT(..., silent = true)`); a failed or unknown proof only drops the candidate. Loops whose jumps run a `finally` or leave a labelled block (`followsJumps` false) infer nothing, as their typestates are not followed either. ## Soundness argument A candidate survives only if (a) it is proved from the facts before the loop, and (b) in the last check, assuming all survivors at the head, it is proved at every point where the next iteration starts: the end of the body (if reachable), the update or condition after it, and every `continue` (through the join facts, each proved on every path into the join). So the survivors form an inductive invariant and hold at the head on every iteration; errors are only kept from that last check. An earlier check assumes more candidates (and fewer typestates) than the last one, so an error that stops it is also an error of the last one. Integers are mathematical, as elsewhere in LiquidJava. Checked with Codex (no false negative found) and these programs that must still be rejected: decrementing counter with `_ >= 0`, counter reset in the body, `i = i - 2` on some path, a bound the step breaks (`i += 3` under `i < 10` with `_ <= 10`), a continue path that decreases `i` (in `while`, and in `for` before the update), an inner loop that decreases the outer counter, labelled continue from an inner loop, switch and try/finally in the body. ## Before / after | Program | main | this PR | |---|---|---| | #537 `for (int i = 0; i < 10; i++) use(i)` | `found i < 10 but expected i >= 0` | Correct | | #537 `while (total < 1024) { use(total); total = total + 1; }` | `found total < 1024 but expected total >= 0` | Correct | | #537 buffer loop (`read(buf, total, limit - total)` with `off >= 0`, `if (n < 0) break; total += n;`) | `found total < limit but expected total >= 0` | Correct | | #538 bounded accumulation (`@Refinement("_ >= 0 && _ <= 1024") total`, guard then `total = total + n`) | Refinement Error | Correct (with #549) | | #479 `for (int i = 0; i < l.size(); i++) l.get(i)` | `... i < #size_result but expected i >= 0 && i < size(l)` | Correct | #479 needed only `i >= 0`: the list is not havocked (its `size()` and `get` do not change its state), so the plan's #546 (candidates from what the body requires) is not needed for it. ## Tests - `CorrectLoopInvariants` (each method fails without this PR): #537's counter and accumulator, the buffer loop, a symbolic start (`for (int i = k; ...)` after `if (k < 0) return;`), nested loops (`j` starts at `i`), and a continue in `for`, `while` and `do`-`while`. - `ErrorLoopInvariants` (non-inductive candidates must not be assumed): decrementing counter, reset in the body, decreased on some path, bound not kept by the step, decreased before a continue (in `while`, and in `for` before the update), decreased in an inner loop. - `classes/loop_list_index_correct`: the #479 reproducer. ## Timing Full suite, same machine, two runs each (machine shared, so noisy): main 195 s / 170 s wall, TestExamples 127 s / 86 s; this PR 163 s / 142 s wall, TestExamples 98 s / 91 s. On the same pair of runs, the 16 existing loop fixtures take 1.3 to 2 times as long (e.g. `CorrectLoopStateFixpoint` 2.3 s to 3.6 s, `CorrectLoopCondition` 0.37 s to 0.79 s): each check of a loop body now also runs one silent SMT query per candidate, and a dropped candidate costs one more check of the body. Tuning (caps, nested loops re-inferred per outer check) is #547. ## Known precision gaps (from the Codex review, left for later) - A `for` update or `do`-`while` condition that repairs a value set before a `continue` (`i = -1; continue;` then `i++`) is not followed: the join keeps only facts proved before the update. - A `finally` anywhere on a jump path turns inference off for the whole loop, as for typestates. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Fixes #538
What and why
A path condition (the condition of an
if, a loop, a ternary) is stored twice: on the variable names (n <= 10 - t) and on the instances the condition was checked on (n@1 <= 10 - t@0). A plain name always means the variable's last instance. Assigning a variable dropped every path condition that mentioned it, so a guard written to keep an assignment in range did not prove it.Changes:
TypeChecker.checkVariableRefinements, used by assignments,+=,++/--and declarations; andforgetChanges, used by loop/switch havoc), its name in the path conditions is replaced by its current last instance (VCChecker.keepPathVariablesOnCurrentValue). Conditions are still dropped when the variable has no instance to name its old value, and for objects (they also get new instances on state changes, which do not go through this method).x++/x--no longer keep a stale condition (pre-existing false negative, same root): increments did not touch the path conditions at all, soif (t < 5) { t++; lessThanFive(t); }was accepted on main (t < 5was read on the incremented value).visitCtIfscanned the else branch with the path conditions the then branch left (e.g. from a nestedif (t > 0) return;), and kept both branches' conditions after the if. Now each branch starts from the conditions before theif; after it, only the conditions both branches kept remain, or those of the only branch that reaches the code after theif(as that branch left them, renames included).x == yafterint x = y) named the parameter itself, which stands for its last instance, so it changed meaning onceywas written (int x = y; if (x > 0) { y = -1; positive(-1); }is accepted on main).snapshotWrittenParametersgives such parameters an entry instance when the method or constructor is checked.TryCheckeris unchanged: after afinally, the name of a variable thefinallychanged refers to thefinally's value, not to the value the try's conditions were checked on, so renaming there would be wrong; dropping stays.Soundness argument
Variable.getRefinementisx == x@last && ...), so the renamed condition says exactly what the condition said just before; instances never change, so it stays true for the rest of the path. Every way a primitive variable gets a new instance either goes through the rename (assignments, increments, declarations, havoc) or happens after the branch assignments that renamed it (if joins,try"any of" instances); a variable declared again in a sibling block gets a newVariablewithout instances, so conditions on the old name are dropped.removePathVariable,restorePathVariables) still find them; a renamed condition is valid on every path where the original was, including the other branch of an if (the rename names the value from before the if).Before / after
#538 reproducer (guarded) and early-exit form:
ErrorGuardedAssignment.incremented(t++undert < 5)ErrorGuardedAssignment.parameterWrittenAfterCopyErrorNestedIfPathCondition(both methods)expected t <= 0 but could not prove it)#537, #479 and the buffer loop from #537 are unchanged by this PR (they need the loop invariant PRs, stacked on this one).
Tests
CorrectGuardedAssignment: False error: an if condition that mentions a variable is dropped when that variable is assigned (if (n <= 10 - t) t = t + n) #538's guarded and early-exit forms, and an else branch that uses its condition after the then branch assigned the variable (all fail on main).ErrorGuardedAssignment: the guard is not applied to the new value after an assignment; nor aftert++(accepted on main); nor after an if where only the branch that assigned continues (accepted by a version of this change that reset the condition to its plain-name form at the join); a copy of a parameter keeps its entry value after the parameter is written (accepted on main).ErrorNestedIfPathCondition: a nested if's condition does not hold in the other branch, nor after both branches (both accepted on main).ErrorIfAssignment.ifAssignment2assigned in a branch that cannot run (a == 5is never< 0); it is now proved unreachable, so its guard is changed toa > 0to keep the assignment checked.TestCounterexamples.variableUpdateIncludesNegativeInputAndGeneratedReturn: the counterexample now names the parameter's entry value#x(shown asx; the message is unchanged).Full suite passes locally (
mvn -q test), same wall-clock as main (about 4 min including the build).🤖 Generated with Claude Code